<template>
  <div id="three"></div>
</template>

<script lang='ts' setup>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
// import Stats from 'three/examples/jsm/libs/stats.moduel.js'

import { onMounted  } from 'vue'


//创建一个三维场景
const scene = new THREE.Scene()

//创建 正方形 几何体
const box = new THREE.BoxGeometry(100, 100, 100)

//创建 网格材质（外观）
const material = new THREE.MeshLambertMaterial({
  color: 0x00ffff,//设置材质颜色
  transparent: true,//开启透明度
  opacity: 0.5 //设置透明度
})
// 跟据 【形状、外观】 => 创建一个网格模型对象
const mesh1 = new THREE.Mesh(box, material)
// 设置网格模型的 摆放 位置
mesh1.position.set(50, 50, 50)
//把网格模型添加到三维场景
scene.add(mesh1)

// 创建 球形 几何体
const sphere = new THREE.SphereGeometry(60)
// 跟据 【形状、外观】 => 创建一个网格模型对象
const mesh2 = new THREE.Mesh(sphere, material)
// 设置网格模型的 摆放 位置
mesh2.position.set(200, 50, 50)
//把网格模型添加到三维场景
scene.add(mesh2)

//添加 环境光
const ambient = new THREE.AmbientLight(0xffffff, 1.0)
scene.add(ambient)

// 点光源
const light1 = new THREE.PointLight(0xffffff, 1000)
light1.position.set(200, 200, 600)
light1.decay = 0.0 // 不受 距离影响 而衰减
scene.add(light1)
// 可视化 点光源
const pointLightHelper = new THREE.PointLightHelper(light1, 10, 0x0000ff)
scene.add(pointLightHelper)

// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0)
directionalLight.position.set(200, 200, 200)
directionalLight.target = mesh1
scene.add(directionalLight)

// 可视化 平行光
const directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight, 10, 0xffff00)
scene.add(directionalLightHelper)


//创建 坐标轴
const axesHelper = new THREE.AxesHelper(1000)
scene.add(axesHelper)


//创建一个透视相机
const width = window.innerWidth, height = window.innerHeight
const camera = new THREE.PerspectiveCamera(45, width/height, 1, 2000)
//设置相机位置
camera.position.set(500, 500, 1000) 
//设置相机方向
camera.lookAt(mesh1.position)

// 显示 帧率
// const stats = new Stats()
// document.body.appendChild(stats.domElement)


//创建一个 WebGL 渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height)
renderer.render(scene, camera)

// 相机控件： 鼠标控制 旋转 缩放
const controls = new OrbitControls(camera, renderer.domElement)
// controls.target.set(500, 500, 500)
// controls.update()
controls.addEventListener('change', () => {
  renderer.render(scene, camera)
})

onMounted(()=>{
  document.getElementById('three')?.appendChild(renderer.domElement)

  // render()
})

// 渲染循环 开启动画
const render = () => {
  mesh1.rotateY(0.01)
  renderer.render(scene, camera)
  requestAnimationFrame(render)
}

// 画布 跟随 浏览器 窗口变化而更新
window.onresize = () => {
  renderer.setSize(window.innerWidth, window.innerHeight)
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.render(scene, camera)
}
</script>

<style lang='scss'>
body{
  margin: 0;
  padding: 0;
}
</style>